import { styled } from "linaria/react";
import { View, Text, ScrollView, Button } from "@tarojs/components";
import { request, showToast, switchTab, useReady } from "@tarojs/taro";
import React, { ReactElement, useState } from "react";
import Background from "../../common/Background";
import { Blog } from "../../api/types";
import BlogCard from "../../components/BlogCard";

const Index = (): ReactElement => {
  const [blogs, setBlogs] = useState<Blog[]>([]);
  console.log(blogs);
  useReady(() => {
    request({
      url: "https://api.hongbin.xyz:3002/getBlogs",
      data: {
        verify: false,
        limit: 5,
        skip: 0,
        find: {
          status: "公开"
        },
        sort: {
          createAt: -1
        }
      },
      method: "GET",
      header: {
        "content-type": "application/json"
      },
      success: function({ data }) {
        setBlogs(data.blogs);
      },
      fail: function() {
        showToast({ title: "请求失败", icon: "error", duration: 2000 });
      }
    });
  });

  return (
    <Container scrollY>
      <Background />
      <Title>
        <Text>你好 旅行者👏</Text>
      </Title>
      {blogs.length ? (
        <FadeView>
          {blogs.map(blog => (
            <BlogCard key={blog._id} blog={blog} />
          ))}
          <Button
            onClick={() => {
              switchTab({
                url: "/pages/blogList/index"
              });
            }}
            className="primaryButton"
          >
            更多 前往博客列表
          </Button>
        </FadeView>
      ) : null}
    </Container>
  );
};

export default Index;

const Title = styled(View)`
  height: 30vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;

  text {
    display: block;
    font-weight: bold;
    color: #ffffff;
    font-size: 2rem;
    letter-spacing: 2px;
    animation: fade 1s linear;
    transform: translateY(-100%);
  }

  @keyframes fade {
    from {
      opacity: 0;
      transform: translateY(0);
      font-size: 1rem;
    }
    to {
      opacity: 1;
      transform: translateY(-100%);
      font-size: 2rem;
    }
  }
`;

const Container = styled(ScrollView)`
  width: 100vw;
  height: 100vh;
  position: relative;

  button {
    width: 90vw;
    margin-bottom: 5rem;
  }
`;

export const FadeView = styled(View)`
  animation: fadeShow 0.4s ease-out;

  @keyframes fadeShow {
    from {
      opacity: 0;
      transform: translateY(5rem);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
`;
